package com.zhiche.lisa.core.utils;

import com.alibaba.fastjson.JSONObject;
import com.zhiche.lisa.core.supports.BaseException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

/**
 * 用于调用微信，目前主要获取openId
 * User: fanguangji
 * Date: 2018/11/27
 */
public class WeiXinUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(WeiXinUtil.class);

    //请求公共的url
    public static final String COMMON_URL = "https://api.weixin.qq.com/";

    //从微信端获取openid的url
    public static final String QUERY_OPENID_URL = COMMON_URL + "sns/oauth2/access_token?&grant_type=authorization_code&appid=";

    //appid 微信公众号id
    public static final String APPID = "wxccb4595a292c7293";

    //公众号的appSecret(一个公众号对应一个appSecret)
    public static final String APP_SECRET = "a0230bf2c876e0db313b6f3e4c706440";

    /**
     *  根据微信code获取微信openId
     * @param code 微信code
     * @return String
     */
    public static String getOpenIdByCode (String code) {
        String openId = null;

        try {
            //获取返回的code
            JSONObject jsonObject = doGetRequest(code);
            LOGGER.info("获取openid返回的jsonObject:" + jsonObject);

            if(Objects.nonNull(jsonObject.getString("openid"))){
                openId = jsonObject.getString("openid");
                LOGGER.info("获取openId的结果为：openId=", openId);
            }
        }catch (Exception e){
            throw new BaseException("获取微信openId异常：" + e);
        }
        return openId;
    }

    /**
     * get方式调用微信接口,无参数传递
     *
     * @param code 微信code
     * @return 将请求url返回的结果转为json格式并返回
     */
    public static JSONObject doGetRequest (String code) {
        JSONObject jsonObject = null;
        try {
            //组装获取openid的连接参数
            String openIdUrl = setOpenIdParam(code);
            //获取defaultHttpClient请求
            HttpClient httpClient = HttpClientBuilder.create().build();
            //使用get方式发送url
            HttpGet httpGet = new HttpGet(openIdUrl);
            //使用HTTPResponse获取微信发送请求结果
            HttpResponse response = httpClient.execute(httpGet);
            //从request获取结果，类型为httpEntity
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                String result = EntityUtils.toString(entity, "UTF-8");
                jsonObject = JSONObject.parseObject(result);
            }
        } catch (Exception e) {
           throw new BaseException("调用微信异常：" + e);
        }
        return jsonObject;
    }

    /**
     * 获取openid和access_token的连接
     */
    public static String setOpenIdParam (String code) {
        StringBuffer getAccessToken = new StringBuffer();
        getAccessToken.append(QUERY_OPENID_URL);
        getAccessToken.append(APPID);
        getAccessToken.append("&secret=");
        getAccessToken.append(APP_SECRET);
        getAccessToken.append("&code=");
        getAccessToken.append(code);
        return getAccessToken.toString();
    }

}
